// pages/confirmation/confirmation.js
let util = require('../../utils/util');
const api = require('../../utils/api');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeGoods: app.global.activeGoods,
    quanKuan: 0,
    shouKuan: 0,
    weiKuan: 0,
    address: {},
    defaultAddress: [],
    moren: ""
  },
  //跳至支付框
  showPay(e) {
    let price = e.target.dataset.price
    wx.navigateTo({
      url: '../../pages/payment/payment?price=' + price,
    })
  },
  //跳至地址列表页
  locaList() {
    wx.navigateTo({
      url: '../../pages/idAddress/idAddress'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    let that = this;

    // 请求所有地址,并加载默认地址
    util.myRequest(api.addressList, {},
      res => {
        let addressList = res.data.data,
          len = addressList.length;
        for (let i = 0; i < len; i++) {
          // 判断是否是默认地址
          if (addressList[i].is_default === 1) {
            that.setData({
              address: addressList[i]
            })
            break;
          }
        }
        // 判断用户手动选择的地址是否存在,如果存在,加载手动选择的地址
        if (app.global.address.name) {
          this.setData({
            address: app.global.address,
          })
        }
      }
    )
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    this.setData({
      activeGoods: app.global.activeGoods,
    })

    let count = 0;
    app.global.activeGoods.forEach(item => count += item.retail_price * item.number)
    this.setData({
      quanKuan: count,
      shouKuan: Math.floor(count * 0.1),
      weiKuan: Math.floor(count * 0.9)
    })
  },

  /**
   * 
   * @param {事件对象} e 
   */
  tapOrder(e) {
    let id = e.target.dataset.id;
    if (id === 1) {
      console.log(this.data.address);
      util.myRequest(api.orderSubmit, {
          addressId: this.data.address.id,
          couponId: ''
        }, res => {
          console.log(res);
        },
        'post')
    }
  }

})